import { isUndef } from "../../help";
function createInvoker(originalFn){
    const invoker = (event)=>{
        // 只触发自己dom身上的事件
        if (event.target === event.currentTarget){
            return originalFn.call(this, event);
        }
    };
    return invoker;
}
function updateDOMListener(oldVnode, vnode){
    const data = vnode.data || {};
    const oldData = oldVnode.data || {};
    const on = data.on || {};
    const oldOn = oldData.on || {};

    const elm = vnode.elm;
    
    
    let name;
    for (name in on){
       const invoker = createInvoker(on[name]);
       on[name] = invoker;
       if (isUndef(oldOn[name])){
            addEvent(elm, name, invoker);
       }else{
            oldOn[name] = invoker;
       }
    }
    for (name in oldOn){
        if (isUndef(on[name])){
            removeEvent(elm, name, oldOn[name]);
        }
    }

    
}
function removeEvent(elm, name, invoker){
    elm.removeEventListener(name, invoker);
}
function addEvent(elm, name, invoker){
    elm.addEventListener(name, invoker);
}
export default{
    create: updateDOMListener,
    update: updateDOMListener
}